using System;
using System.Collections;
using UnityEngine;

namespace NodeCanvas.DialogueTrees
{
	[AddComponentMenu("NodeCanvas/Dialogue Actor")]
	public class DialogueActor : MonoBehaviour
	{
		[SerializeField]
		private string _actorName;

		public Texture2D portrait;

		public Color dialogueColor = Color.white;

		public Vector3 dialogueOffset;

		public Blackboard blackboard;

		public string actorName
		{
			get
			{
				return _actorName;
			}
			set
			{
				_actorName = value;
			}
		}

		public string speech { get; set; }

		public Vector3 dialoguePosition
		{
			get
			{
				return Vector3.Scale(base.transform.position + dialogueOffset, base.transform.localScale);
			}
		}

		private void Reset()
		{
			actorName = base.gameObject.name;
		}

		public void Say(string text, Action callback)
		{
			Say(new Statement(text), callback);
		}

		public void Say(Statement statement, Action callback)
		{
			speech = null;
			if (!EventHandler.Dispatch(DLGEvents.OnActorSpeaking, new DialogueSpeechInfo(this, statement, callback)))
			{
				Debug.LogWarning("Make sure you have added the default <b>@DialogueGUI</b> prefab, or you have created your own UI to handle the events");
			}
		}

		public void StopTalking()
		{
			speech = null;
			EventHandler.Dispatch(DLGEvents.OnDialogueFinished);
		}

		public IEnumerator ProcessStatement(Statement statement, Action callback)
		{
			if ((bool)statement.audio)
			{
				AudioSource audioSource = base.gameObject.AddComponent<AudioSource>();
				audioSource.PlayOneShot(statement.audio);
				float timer = 0f;
				speech = statement.text;
				while (timer < statement.audio.length)
				{
					timer += Time.deltaTime;
					yield return null;
				}
				UnityEngine.Object.DestroyImmediate(audioSource);
			}
			else
			{
				for (int i = 0; i < statement.text.Length; i++)
				{
					speech += statement.text[i];
					yield return new WaitForSeconds(0.05f);
					char c = statement.text[i];
					if (c == '.' || c == '!' || c == '?')
					{
						yield return new WaitForSeconds(0.5f);
					}
					if (c == ',')
					{
						yield return new WaitForSeconds(0.1f);
					}
				}
				yield return new WaitForSeconds(1.2f);
			}
			speech = null;
			callback();
		}

		private void OnDrawGizmos()
		{
			Gizmos.DrawLine(base.transform.position, dialoguePosition);
		}

		public static DialogueActor FindActorWithName(string name)
		{
			UnityEngine.Object[] array = UnityEngine.Object.FindObjectsOfType(typeof(DialogueActor));
			for (int i = 0; i < array.Length; i++)
			{
				DialogueActor dialogueActor = (DialogueActor)array[i];
				if (dialogueActor.actorName == name)
				{
					return dialogueActor;
				}
			}
			return null;
		}
	}
}
